const express = require('express');
const router = express.Router();
const { User } = require('../../models')
const{ Op } = require('sequelize')
const {NotFoundError,success,failure} = require('../../utils/response')

//查询列表
router.get('/',async function(req, res, next) {
    try{
        const query = req.query
        //当前页数
        const currentPage = Math.abs(Number(query.currentPage))||1
        //每页显示条数
        const pageSize = Math.abs(Number(query.pageSize))||10 
        const offset = (currentPage-1)*pageSize
        const condition ={
            order:[['id','ASC']],
            limit:pageSize,
            offset:offset
        }
        if (query.email) {
            condition.where = {
              email: {
                [Op.eq]: query.email
              }
            };
          }
          
          if (query.username) {
            condition.where = {
              username: {
                [Op.eq]: query.username
              }
            };
          }
          
          if (query.nickname) {
            condition.where = {
              nickname: {
                [Op.like]: `%${ query.nickname }%`
              }
            };
          }
          
          if (query.role) {
            condition.where = {
              role: {
                [Op.eq]: query.role
              }
            };
          }
          
        const {count,rows} = await User.findAndCountAll(condition)
        success(res,'查询列表成功',{
            users:rows,
            pagination:{
                total:count,
                currentPage:currentPage,
                pageSize:pageSize
            }
        },200)
    }catch(error){
        failure(res,error)
    }
    
});

//查询详情
router.get('/:id',async function(req, res, next) {
    try{
        const user = await getUser(req)
        success(res,'查询成功',{ 
            user
        },201) 
    }catch(error){
        failure(res,error)
    }
    
});

//创建
router.post('/',async function(req, res, next) {
    try{
        //白名单过滤
        const body=filterBody(req)
        const user = await User.create(body)
        success(res,"创建成功",{user},201) 
    }catch(error){
        failure(res,error)
    }
    
});


//更新
router.put('/:id',async function(req, res, next) {
    try{
        const user = await getUser(req)
        const body = filterBody(req)
        await user.update(body)
        res.json({
            status:true,
            message:"更新用户成功",
            data:user
        })  
    }catch(error){
        res.status(500).json({
            status:false,
            message:"更新用户失败",
            errors:[error.message]
        })
    }
});

//公共方法：查询
async function getUser(req){
    const {id} = req.params
    //查询当前用户
    const user= await User.findByPk(id)
    if(!user){
        throw new NotFoundError(`ID:${id}的用户未找到`)
    }
    return user
}

//白名单过滤
function filterBody(req){
    return {
        email: req.body.email,
        username: req.body.username,
        password: req.body.password,
        nickname: req.body.nickname,
        sex: req.body.sex,
        company: req.body.company,
        introduce: req.body.introduce,
        role: req.body.role,
        avatar: req.body.avatar
      };
}


module.exports = router;
